package com.ssms.service;

import com.ssms.commons.Result;
import com.ssms.commons.TablePage;
import com.ssms.dao.*;
import com.ssms.model.*;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Service
public class XjApplyService {

    @Resource
    private StuDetailMapper stuDetailMapper;
    @Resource
    private XjApplyMapper xjApplyMapper;
    @Resource
    private ClazzMapper clazzMapper;

    // 有申请在审核中不可再次提交，或者学籍已不是在读状态，也不可提交
    public Result save(XjApply xjApply) {
        StuDetail stuDetail = stuDetailMapper.selectByStuId(xjApply.getStuId());
        if(!"在读".equals(stuDetail.getXj())){
            return Result.failed("您学籍处于【"+stuDetail.getXj()+"】状态,不可变更！", 500);
        }

        if(xjApplyMapper.checkRepeat(xjApply) > 0){
            return Result.failed("您已有申请在审核中，请勿重复申请", 500);
        }

        int count = xjApplyMapper.insertSelective(xjApply);
        return count > 0?Result.success():Result.failed("添加失败", 500);
    }

    // 学籍异动申请分页查询，辅导员只能看自己班级的，学生只能看自己的
    public TablePage search(TablePage tablePage, String val,Integer fdyId,Integer stuId) {
        List<XjApply> list = new ArrayList<>();
        int count = 0;
        int size = tablePage.getLimit();
        int start = (tablePage.getPage() - 1) * size;

        // 辅导员
        List<Clazz> clazzes = clazzMapper.selectByInstructor(fdyId);
        if(clazzes != null && clazzes.size() > 0){
            List<Integer> clzIds = new ArrayList<>();
            for (Clazz clazz : clazzes) {
                clzIds.add(clazz.getId());
            }
            list = xjApplyMapper.selectPage(start,size,val,stuId,clzIds);
            count = xjApplyMapper.selectPageCount(val,stuId,clzIds);
        }

        // 学生
        if(stuId != null){
            list = xjApplyMapper.selectPage(start,size,val,stuId,null);
            count = xjApplyMapper.selectPageCount(val,stuId,null);
        }

        tablePage.setCount(count);
        tablePage.setData(list);
        return tablePage;
    }


    public Result update(XjApply xjApply) {

        int count = xjApplyMapper.updateByPrimaryKeySelective(xjApply);
        if(count > 0  && xjApply.getStatus() == 1){
            StuDetail stuDetail = new StuDetail();
            stuDetail.setUserId(xjApply.getStuId());
            if(xjApply.getTypes() == 1){
                stuDetail.setXj("退学");
            }else{
                stuDetail.setXj("休学");
            }
            stuDetailMapper.updateByPrimaryKeySelective(stuDetail);
        }
        return count > 0?Result.success():Result.failed("更新失败", 500);
    }

    public Result delete(Integer id) {
        xjApplyMapper.deleteByPrimaryKey(id);
        return Result.success();
    }
}
